﻿using AiCar.Gauge;
using AiCar.Utils;
using CefSharp;
using Service.Utility;
using System;
using System.Threading;
using System.Windows;
using Utility;

namespace AiCar
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        GridLength m_WidthCache;

        private bool W = false;
        private bool A = false;
        private bool S = false;
        private bool D = false;
        private bool R = false;
        private bool Q = false;
        private bool E = false;

        /// <summary>
        /// 调速定时器
        /// </summary>
        System.Windows.Forms.Timer QETimer = new System.Windows.Forms.Timer();

        /// <summary>
        /// 键盘Hook
        /// </summary>
        private HOOK _Keyboardhook;
        public object DispatcherHelper { get; private set; }

        public MainWindow()
        {
            this.DataContext = new GaugeViewModel();

            InitializeComponent();

            
        }

        public void VlcPlay()
        {
            //需要安装vlc客户端以后弃用, 树莓派推rtsp流延迟高并且内存占用高,改http流
            //this.vlcControl.SourceProvider.CreatePlayer(new System.IO.DirectoryInfo(@"C:\Program Files\VideoLAN\VLC"));
            //this.vlcControl.SourceProvider.MediaPlayer.Play(new Uri(@"http://192.168.137.78:8080/?action=stream --newwork-caching=300"));

            Button_Click(null, null);

            //初始化键盘钩子
            _Keyboardhook = new HOOK();
            if (_Keyboardhook.Start())
            {
                LogWrite("键盘钩子安装成功");
                _Keyboardhook.KeyPressEvent += HOOK_KeyPress;
                //_Keyboardhook.KeyDownEvent += HOOK_KeyDown;
                _Keyboardhook.KeyUpEvent += HOOK_KeyUp;
            }
            else
            {
                LogWrite("键盘钩子安装失败");
            }
        }

        public class MenuHandler : IContextMenuHandler
        {
            public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
            {
                model.Clear();
            }
            public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
            {
                return false;
            }
            public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
            {
            }
            public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
            {
                return false;
            }
        }

        /// <summary>
        /// 键盘松开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HOOK_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            new Thread(new ThreadStart(() =>
            {
                switch (e.KeyCode.ToString())
                {
                    case "A":
                    case "a":
                        if (A)
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/Stop");
                            A = false;
                        }
                        break;
                    case "s":
                    case "S":
                        if (S)
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/Stop");
                            S = false;
                        }
                        break;
                    case "w":
                    case "W":
                        if (W)
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/Stop");
                            W = false;
                        }
                        break;
                    case "D":
                    case "d":
                        if (D)
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/Stop");
                            D = false;
                        }
                        break;
                    case "R":
                    case "r":
                        if (R)
                            R = false;
                        break;
                    case "q":
                    case "Q":
                    case "Oemcomma":
                        if (Q)
                        {
                            Q = false;
                            if (!E)
                            {
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    QETimer.Stop();
                                }));
                            }
                        }
                        break;
                    case "E":
                    case "e":
                    case "OemPeriod":
                        if (E)
                        {
                            E = false;
                            if (!Q)
                            {
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    QETimer.Stop();
                                }));
                            }
                        }
                        break;
                    default:
                        return;
                }
            })).Start();
        }

        /// <summary>
        /// 键盘按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HOOK_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
        }

        /// <summary>
        /// 键盘按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HOOK_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            new Thread(new ThreadStart(()=> 
            {
                switch (e.KeyChar)
                {
                    case 'A':
                    case 'a':
                        if (A)
                            return;
                        else
                        {
                            A = true;
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/left");
                        }
                        break;
                    case 's':
                    case 'S':
                        if (S)
                            return;
                        else
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/down");
                            S = true;
                        }
                        break;
                    case 'w':
                    case 'W':
                        if (W)
                            return;
                        else
                        {
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/up");
                            W = true;
                        }
                        break;
                    case 'D':
                    case 'd':
                        if (D)
                            return;
                        else
                        {
                            D = true;
                            HttpUtility.HttpGet<object>("http://192.168.137.78:5000/api/Motor/right");
                        }
                        break;
                    case 'r':
                    case 'R':
                        if (R)
                            return;
                        else
                            R = true;
                        break;
                    case 'Q':
                    case 'q':
                    case ',':
                        if (Q)
                            return;
                        else
                        {
                            Q = true;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                QETimer.Start();
                            }));
                        }
                        break;
                    case 'E':
                    case 'e':
                    case '.':
                        if (E)
                            return;
                        else
                        {
                            E = true;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                QETimer.Start();
                            }));
                        }
                        break;
                    default:
                        return;
                }
            })).Start();
        }


        /// <summary>
        /// 初始化
        /// </summary>
        private void Window_Initialized(object sender, EventArgs e)
        {
            VlcPlay();
            _Keyboardhook.ChangeLanguage();
            //给timer挂起事件
            QETimer.Tick += new EventHandler(QECallback);
            //使timer可用
            //QETimer.Enabled = true;
            //设置时间间隔，以毫秒为单位
            QETimer.Interval = 10;

            //防止输出框内存泄漏
            log.UndoLimit = 0;

            

        }

        private void QECallback(object sender, EventArgs e)
        {
            GaugeViewModel mode = (GaugeViewModel)DataContext;
            if (Q)
                mode.Value--;
            if (E)
                mode.Value++;
            string url = "http://192.168.137.78:5000/api/Motor/rev?values=" + (mode.Value * 5);
            HttpUtility.HttpGet<ReturnMsg<int>>(url);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GridLength temp = grdWorkbench.ColumnDefinitions[2].Width;
            GridLength def = new GridLength();
            if (temp.Equals(def))
            {
                mian.Visibility = Visibility.Visible;
                shrink.Content = "  》";
                //恢复
                grdWorkbench.ColumnDefinitions[2].Width = m_WidthCache;
            }
            else
            {
                shrink.Content = "《";
                mian.Visibility = Visibility.Collapsed;
                //折叠
                m_WidthCache = grdWorkbench.ColumnDefinitions[2].Width;
                grdWorkbench.ColumnDefinitions[2].Width = def;
            }
            Console.WriteLine();
        }
        //private void play_Button_Click(object sender, RoutedEventArgs e)
        //{
        //    this.vlcControl.SourceProvider.MediaPlayer.Play(new Uri(url_TextBox.Text));
        //}

        //private void pause_Button_Click(object sender, RoutedEventArgs e)
        //{
        //    this.vlcControl.SourceProvider.MediaPlayer.Pause();
        //}

        public void LogWrite(string values)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                //多次数操作字符串使用AppendText，否则会造成内存泄漏
                log.AppendText($"\n{DateTime.Now}\n{values}");
                log.ScrollToEnd();
            }));
        }

        private void help_Click(object sender, RoutedEventArgs e)
        {
            Help hp = new Help();
            hp.ShowDialog();
        }


        /// <summary>
        /// 关闭时释放资源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, EventArgs e)
        {
            _Keyboardhook.RecoverLanguage();
            QETimer.Dispose();
            _Keyboardhook.Stop();
        }

        private void changeLanguage_Click(object sender, RoutedEventArgs e)
        {
            if (changeLanguage.Content.Equals("恢复输入法"))
            {
                changeLanguage.Content = "禁用输入法";
                _Keyboardhook.RecoverLanguage();
            }
            else
            {
                changeLanguage.Content = "恢复输入法";
                _Keyboardhook.ChangeLanguage();
            }
        }

        private void guageSet_Click(object sender, RoutedEventArgs e)
        {
            if (guageSet.Content.Equals("隐藏仪表盘"))
            {
                guageSet.Content = "显示仪表盘";
                guage.Visibility = Visibility.Collapsed;
            }
            else
            {
                guageSet.Content = "隐藏仪表盘";
                guage.Visibility = Visibility.Visible;
            }
        }
    }
}
